// DOM元素
const stockForm = document.getElementById('add-stock-form');
const stockList = document.getElementById('stock-list');
const stockModal = document.getElementById('stock-modal');
const modalClose = document.querySelector('.close');
const modalStockName = document.getElementById('modal-stock-name');
const modalStockDetails = document.getElementById('modal-stock-details');
const refreshBtn = document.getElementById('refresh-btn');

// 页面加载时获取股票列表
document.addEventListener('DOMContentLoaded', () => {
  fetchStocks();
  
  // 每10秒刷新一次股票数据
  setInterval(fetchStocks, 10000);
});

// 刷新按钮事件
if (refreshBtn) {
  refreshBtn.addEventListener('click', async () => {
    // 禁用按钮并显示加载状态
    refreshBtn.disabled = true;
    refreshBtn.textContent = '🔄 刷新中...';
    
    try {
      // 手动触发股票数据更新
      await fetch('/api/stocks/update', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      // 等待1秒后刷新页面数据
      setTimeout(() => {
        fetchStocks();
      }, 1000);
      
    } catch (error) {
      console.error('手动刷新失败:', error);
      alert('刷新失败，请稍后重试');
    } finally {
      // 恢复按钮状态
      setTimeout(() => {
        refreshBtn.disabled = false;
        refreshBtn.textContent = '🔄 刷新数据';
      }, 2000);
    }
  });
}

// 添加股票表单提交事件
if (stockForm) {
  stockForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const codeInput = document.getElementById('stock-code');
    const nameInput = document.getElementById('stock-name');
    
    const code = codeInput.value.trim();
    const name = nameInput.value.trim();
    
    if (!code) {
      alert('请输入股票代码');
      return;
    }
    
    try {
      const response = await fetch('/api/stocks', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ code, name })
      });
      
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || '添加股票失败');
      }
      
      // 清空表单
      codeInput.value = '';
      nameInput.value = '';
      
      // 刷新股票列表
      fetchStocks();
    } catch (error) {
      alert(error.message);
    }
  });
}

// 获取所有股票
async function fetchStocks() {
  if (!stockList) return;
  
  // 显示加载状态
  stockList.innerHTML = '<div class="loading">正在加载股票数据...</div>';
  
  try {
    // 添加随机参数避免缓存
    const timestamp = new Date().getTime();
    const response = await fetch(`/api/stocks?_=${timestamp}`);
    
    let stocks = [];
    
    // 即使响应不是200也尝试解析JSON
    try {
      const data = await response.json();
      if (Array.isArray(data)) {
        stocks = data;
      } else {
        console.warn('获取股票列表返回了非数组数据:', data);
      }
    } catch (parseError) {
      console.error('解析股票数据失败:', parseError);
    }
    
    // 无论如何都渲染股票列表
    renderStockList(stocks);
  } catch (error) {
    console.error('获取股票列表失败:', error);
    // 显示错误信息，但仍然渲染空列表
    renderStockList([]);
  }
}

// 渲染股票列表
async function renderStockList(stocks) {
  if (!stockList) return;
  
  // 清空列表
  stockList.innerHTML = '';
  
  if (stocks.length === 0) {
    stockList.innerHTML = '<div class="no-stocks">暂无股票，请添加股票</div>';
    return;
  }
  
  // 获取每只股票的最新价格
  for (const stock of stocks) {
    try {
      const priceResponse = await fetch(`/api/stocks/${stock.id}/price?t=${Date.now()}`);
      
      if (priceResponse.ok) {
        const priceData = await priceResponse.json();
        renderStockCard(stock, priceData);
      } else {
        renderStockCard(stock, null);
      }
    } catch (error) {
      console.error(`获取股票 ${stock.code} 价格失败:`, error);
      renderStockCard(stock, null);
    }
  }
}

// 渲染单个股票卡片
function renderStockCard(stock, priceData) {
  const card = document.createElement('div');
  card.className = 'stock-card';
  card.dataset.id = stock.id || 0;
  
  let priceHtml = '<div class="loading">加载价格中...</div>';
  
  if (priceData) {
    // 确保所有价格数据都是有效的数字
    const price = parseFloat(priceData.price) || 0;
    const openPrice = parseFloat(priceData.open_price) || price;
    const highPrice = parseFloat(priceData.high_price) || price;
    const lowPrice = parseFloat(priceData.low_price) || price;
    
    // 计算价格变化（基于昨日收盘价）
    const yesterdayClosePrice = parseFloat(priceData.yesterday_close_price) || parseFloat(priceData.yesterdayClosePrice) || openPrice;
    const priceChange = yesterdayClosePrice ? (price - yesterdayClosePrice) : 0;
    const priceChangePercent = yesterdayClosePrice ? (((priceChange) / yesterdayClosePrice * 100) || 0).toFixed(2) : '0.00';

    const priceChangeClass = priceChange >= 0 ? 'up' : 'down';
    
    priceHtml = `
      <div class="price-info">
        <div class="current-price">
          <span class="value ${priceChangeClass}">${price.toFixed(2)}</span>
        </div>
        <div class="price-change">
          <span class="value ${priceChangeClass}">
            ${priceChange.toFixed(2)} (${priceChangePercent}%)
          </span>
        </div>
      </div>
      <div class="price-details">
        <div class="detail-item">
          <span class="label">开盘价:</span>
          <span class="value">${openPrice.toFixed(2)}</span>
        </div>
        <div class="detail-item">
          <span class="label">最高价:</span>
          <span class="value up">${highPrice.toFixed(2)}</span>
        </div>
        <div class="detail-item">
          <span class="label">最高涨幅:</span>
          <span class="value ${highPrice - openPrice >= 0 ? 'up' : 'down'}">
            ${(highPrice - openPrice).toFixed(2)} (${((highPrice - openPrice) / openPrice * 100).toFixed(2)}%)
          </span>
        </div>
        <div class="detail-item">
          <span class="label">最低价:</span>
          <span class="value down">${lowPrice.toFixed(2)}</span>
        </div>
        <div class="detail-item">
          <span class="label">最低涨幅:</span>
          <span class="value ${lowPrice - openPrice >= 0 ? 'up' : 'down'}">
            ${(lowPrice - openPrice).toFixed(2)} (${((lowPrice - openPrice) / openPrice * 100).toFixed(2)}%)
          </span>
        </div>
        <div class="detail-item">
          <span class="label">更新时间:</span>
          <span class="value">${new Date(priceData.timestamp).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}</span>
        </div>
      </div>
    `;
  }
  
  card.innerHTML = `
    <h3>${stock.name} (${stock.code})</h3>
    ${priceHtml}
    <div class="actions">
      <a href="/stock/${stock.id}" class="btn btn-primary">详情</a>
      <button class="btn btn-danger delete-btn" data-id="${stock.id}">删除</button>
    </div>
  `;
  
  // 添加删除按钮事件
  const deleteBtn = card.querySelector('.delete-btn');
  deleteBtn.addEventListener('click', (e) => {
    e.stopPropagation();
    deleteStock(stock.id);
  });
  
  // 添加卡片点击事件（显示详情模态框）
  card.addEventListener('click', (e) => {
    if (!e.target.classList.contains('btn')) {
      showStockDetails(stock);
    }
  });
  
  stockList.appendChild(card);
}

// 删除股票
async function deleteStock(id) {
  if (!confirm('确定要删除这只股票吗？')) {
    return;
  }
  
  try {
    const response = await fetch(`/api/stocks/${id}`, {
      method: 'DELETE'
    });
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error || '删除股票失败');
    }
    
    // 刷新股票列表
    fetchStocks();
  } catch (error) {
    alert(error.message);
  }
}

// 显示股票详情模态框
async function showStockDetails(stock) {
  modalStockName.textContent = `${stock.name} (${stock.code})`;
  modalStockDetails.innerHTML = '<div class="loading">加载中...</div>';
  stockModal.style.display = 'block';
  
  try {
    const priceResponse = await fetch(`/api/stocks/${stock.id}/today`);
    
    if (!priceResponse.ok) {
      throw new Error('获取价格数据失败');
    }
    
    const prices = await priceResponse.json();
    
    if (prices.length === 0) {
      modalStockDetails.innerHTML = '<div class="no-data">暂无今日价格数据</div>';
      return;
    }
    
    // 渲染价格表格
    let tableHtml = `
      <table class="price-table">
        <thead>
          <tr>
            <th>时间</th>
            <th>价格</th>
            <th>开盘价</th>
            <th>最高价</th>
            <th>最高价变动</th>
            <th>最低价</th>
            <th>最低价变动</th>
          </tr>
        </thead>
        <tbody>
    `;
    
    prices.forEach(price => {
      const openPrice = price.open_price;
      const highPrice = price.high_price;
      const lowPrice = price.low_price;
      
      const highPriceChange = highPrice - openPrice;
      const highPriceChangePercent = (highPriceChange / openPrice * 100).toFixed(2);
      const highPriceChangeClass = highPriceChange >= 0 ? 'up' : 'down';
      
      const lowPriceChange = lowPrice - openPrice;
      const lowPriceChangePercent = (lowPriceChange / openPrice * 100).toFixed(2);
      const lowPriceChangeClass = lowPriceChange >= 0 ? 'up' : 'down';
      
      tableHtml += `
        <tr>
          <td>${new Date(price.timestamp).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}</td>
          <td>${price.price.toFixed(2)}</td>
          <td>${openPrice.toFixed(2)}</td>
          <td>${highPrice.toFixed(2)}</td>
          <td class="${highPriceChangeClass}">
            ${highPriceChange.toFixed(2)} (${highPriceChangePercent}%)
          </td>
          <td>${lowPrice.toFixed(2)}</td>
          <td class="${lowPriceChangeClass}">
            ${lowPriceChange.toFixed(2)} (${lowPriceChangePercent}%)
          </td>
        </tr>
      `;
    });
    
    tableHtml += `
        </tbody>
      </table>
      <div class="modal-actions">
        <a href="/stocks/${stock.id}" class="btn btn-primary">查看完整历史</a>
      </div>
    `;
    
    modalStockDetails.innerHTML = tableHtml;
  } catch (error) {
    console.error('获取股票详情失败:', error);
    modalStockDetails.innerHTML = `<div class="error">获取数据失败: ${error.message}</div>`;
  }
}

// 关闭模态框
if (modalClose) {
  modalClose.addEventListener('click', () => {
    stockModal.style.display = 'none';
  });
}

// 点击模态框外部关闭
window.addEventListener('click', (e) => {
  if (e.target === stockModal) {
    stockModal.style.display = 'none';
  }
});